package com.mdd.front.controller;

import com.mdd.common.core.AjaxResult;
import com.mdd.common.enums.HttpEnum;
import com.mdd.front.LikeFrontThreadLocal;
import com.mdd.front.service.ICouponService;
import com.mdd.front.validate.commons.PageValidate;
import com.mdd.front.vo.annotation.PreventRepeatSubmit;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 优惠券控制层
 * @author shenjian
 * @createTime 2023年02月27日 21:56:00
 */
@RestController
@RequestMapping("/api/coupon")
public class CouponController {

    /** 领取优惠券异步缓存KEY */
    private static final String COUPON_ISSUING_RECEIVE_REDIS = "COUPON_ISSUING_RECEIVE_";

    @Resource
    ICouponService iCouponService;

    /**
     * 查询个人订单
     * @param pageValidate
     * @param type 1 - 查询有效优惠券，0 - 查询无效优惠券
     * @return
     */
    @GetMapping("/list")
    public AjaxResult<Object> list(@Validated PageValidate pageValidate,
                                   @RequestParam(value = "type", defaultValue = "1") Integer type) {
        return AjaxResult.success(iCouponService.couponList(pageValidate, type));
    }

    /**
     * 查询优惠券领取状态
     * @param sn
     * @return
     */
    @GetMapping("/couponStatus")
    public AjaxResult<?> couponStatus(@Validated @RequestParam(value = "couponSn") String sn) {
        return AjaxResult.success(HttpEnum.SUCCESS.getCode(), HttpEnum.SUCCESS.getMsg(), iCouponService.couponStatus(sn));
    }

    /**
     * 领取优惠券
     * @param sn
     * @return
     */
    @GetMapping("/receive")
    @PreventRepeatSubmit
    public AjaxResult<Object> receive(@Validated @RequestParam(value = "couponSn") String sn) {
        Integer userId = LikeFrontThreadLocal.getUserId();
        String redisKey = COUPON_ISSUING_RECEIVE_REDIS + sn + "_" + userId;
        iCouponService.receiveCoupon(sn, redisKey, userId);
        return AjaxResult.success();
    }

    /**
     * 领取优惠券
     * @param sn
     * @return
     */
    @GetMapping("/receive-test")
    @PreventRepeatSubmit
    public AjaxResult<Object> receive(@Validated @RequestParam(value = "couponSn") String sn,
                                      @RequestParam(value = "userId") Integer userId) {
        String redisKey = COUPON_ISSUING_RECEIVE_REDIS + sn + "_" + userId;
        iCouponService.receiveCoupon(sn, redisKey, userId);
        return AjaxResult.success();
    }

    /**
     * 异步获取状态
     * @param sn
     * @return
     */
    @GetMapping("/receive-result")
    public AjaxResult<Object> receiveResultAsync(@RequestParam(value = "couponSn") String sn) {
        return iCouponService.receiveResultAsync(sn);
    }
}
